import os
import sys
import threading
from threading import Lock,Thread
import time
import logging
import signal
import itertools
root_dir = os.getcwd()
sys.path.append(root_dir)

from recorder.volt_recorder import VoltRecorder
from recorder.inst_conf import InstConfig
import globalvar as gl



logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')  





def sigint_handler(signum, frame):
    gl.set_value('is_sigint_up', True)
    logging.info('### catched interrupt signal!')


def get_sample_parameters():
    sample_parameters = {}
    has_sample_interval = False
    while not has_sample_interval:
        sample_intervals = input('Please input sample intervals (seconds):')
        try:
            sample_interval_secs = int(sample_intervals)
            logging.info('sample intervals (seconds): %d' % sample_interval_secs)
            has_sample_interval = True
            sample_parameters['sample_interval_secs'] = sample_interval_secs
        except ValueError as e:
            logging.error(str(e))

    has_sample_nums = False
    while not has_sample_nums:
        sample_num_in = input('Please input sample nums:')
        try:
            sample_nums = int(sample_num_in)
            logging.info('sample nums: %d' % sample_nums)
            sample_parameters['sample_nums'] = sample_nums  
            has_sample_nums = True
        except ValueError as e:
            logging.error(str(e))       
    return sample_parameters


def run_control():
    time.sleep(1)

    
def main():
    gl._init()
    gl.set_value('is_sigint_up', False)
    cond = threading.Condition()
    gl.set_value('cond', cond)


    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGTERM, sigint_handler)

    sp = get_sample_parameters()

    recorders = []
    p = VoltRecorder(sp['sample_interval_secs'], sp['sample_nums'])
    recorders.append(p)
    p.setDaemon(True) #子线程daemon
    p.start()

    while True:
        alive = False
        for t in itertools.chain(recorders, ): #循环检查所有子线程
                alive = alive or t.is_alive()   #保证所有子线程退出
        if not alive:
            break
        run_control()

if __name__ == '__main__':
    main()

